package com.syl.starter.itools.common.utils.io;

import com.syl.starter.itools.base.constants.BaseConstant;
import com.syl.starter.itools.base.utils.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 获取properties 配置文件的工具类
 *
 * @author syl
 * @create 2018-09-06 16:44
 **/
public class PropertiesUtils {
    private static Logger LOG = LoggerFactory.getLogger(PropertiesUtils.class);
    private static final String PROPERTIES = ".properties";

    /**
     * 从资源文件夹中获取配置文件
     * @param configName 配置文件名称
     * @return
     */
    public static Properties getFileProperties(String configName){
        return getFileProperties(FileUtils.getResourcePath(PropertiesUtils.class),configName);
    }

    /**
     * 从指定的配置文件夹中获取配置文件
     * @param configName 配置文件名称
     * @return
     */
    public static Properties getFileProperties(String dirPath,String configName){
        StringBuffer sb = new StringBuffer();
        sb.append(dirPath)
        .append(File.separator)
        .append(configName.indexOf(BaseConstant.DOT) > -1 ? configName : configName+ PROPERTIES);
        Properties props = new Properties();
        InputStreamReader inputStreamReader;
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(sb.toString()));
            inputStreamReader = new InputStreamReader(fileInputStream, BaseConstant.UTF8);
            props.load(inputStreamReader);
            return props;
        } catch (FileNotFoundException e) {
            LogUtils.error(LOG,"找不到指定文件夹", e);
        } catch (IOException e) {
            LogUtils.error(LOG, "发生io错误",e);
        }
        return null;
    }

    /**
     *  从配置文件中读取String list (list字符串以,号分隔)
     * @param properties
     * @param key
     * @return
     */
    public static List<String> getPropertiesList(Properties properties, String key){
        String property = properties.getProperty(key);
        String[] split = property.split(BaseConstant.MORE_SEPARATOR);
        if(split == null)
            return new ArrayList<>();
        return Arrays.asList(split);
    }

}
